const getPixels = require('get-pixels'),
images = require('images'),
Surf = require('./Surf'),
log = require('../log');

const image_paths = [
	'D:\\androidwork\\jopensurf-master\\src\\test\\resources\\example\\whitehouse1.jpg',
	'D:\\androidwork\\jopensurf-master\\src\\test\\resources\\example\\whitehouse2.jpg'
];

var promiseList = []
image_paths.forEach(path => {
	promiseList.push(new Promise(resolve => {
			getPixels(path, (err, pixels) => {
				if (err) {
					log(err)
					return
				}
				var surf = new Surf({
						width: pixels.shape[0],
						height: pixels.shape[1],
						data: pixels.data
					});
				resolve(surf)
			})
		}))
})
Promise.all(promiseList).then(result => {
	var width = 0,
	height = 0,
	imageList = [];
	image_paths.forEach(path => {
		var image = images(path);
		imageList.push(image)
		var size = image.size();
		if (width < size.width) {
			width = size.width
		}
		if (height < size.height) {
			height = size.height
		}
	})
	var image = images(width * imageList.length, height);
	imageList.forEach((_image, index) => {
		image.draw(_image, width * index, 0)
	})

	var match = result[0].getMatchingPoints(result[1], true);
	match.forEach(item => {
		var point0 = item[0],
		point1 = item[1];
		log(point0.getX() + ' ' + point0.getY() + ' = ' + point1.getX() + ' ' + point1.getY())
		circle(image, point0.getX(), point0.getY(), 11, 0xff, 0x00, 0x00, 0.5)
		circle(image, point1.getX() + width, point1.getY(), 11, 0xff, 0x00, 0x00, 0.5)
		line(image, point0.getX(), point0.getY(), point1.getX() + width, point1.getY(), 0xff, 0x00, 0x00, 0.5)
	})

	image.save(image_paths[0] + '.out.png');
}).catch (err => {
	log(err)
});

function circle(image, x, y, radius, red, green, blue, opacity) {
	var dot = images(1, 1).fill(red, green, blue, opacity);
	for (var i = -radius; i <= radius; i++) {
		var j = Math.round(Math.sqrt(radius * radius - i * i));
		image.draw(dot, x + i, y + j)
		image.draw(dot, x + i, y - j)
	}
}

function line(image, x0, y0, x1, y1, red, green, blue, opacity) {
	var dot = images(1, 1).fill(red, green, blue, opacity);
	var _x0,
	_y0,
	_x1,
	_y1;
	if (x0 < x1) {
		_x0 = x0;
		_y0 = y0;
		_x1 = x1;
		_y1 = y1;
	} else {
		_x0 = x1;
		_y0 = y1;
		_x1 = x0;
		_y1 = y0;
	}
	var gradient = (_y1 - _y0) / (_x1 - _x0);
	for (var i = 0; i <= _x1 - _x0; i++) {
		var j = Math.round(i * gradient);
		image.draw(dot, _x0 + i, _y0 + j)
	}
}
